import { openDB, deleteDB } from 'idb';

const dbPromise = openDB('chat-history-db', 1, {
  upgrade(db) {
    if (!db.objectStoreNames.contains('messages')) {
      db.createObjectStore('messages', { keyPath: 'id', autoIncrement: true });
    }
  }
});

export async function addMessage(message) {
  const db = await dbPromise;
  const tx = db.transaction('messages', 'readwrite');
  const store = tx.store;

  // 添加新消息
  await store.add(message);

  // 获取当前用户的所有消息
  const messages = await store.getAll();
  const userMessages = messages.filter(m => m.userId === message.userId);

  // 如果消息数量超过50条，删除最早的那一条
  if (userMessages.length > 50) {
    const earliestMessage = userMessages.sort((a, b) => a.time - b.time)[0];
    await store.delete(earliestMessage.id);
  }

  await tx.done;
}

export async function getAllMessages(userId) {
  const db = await dbPromise;
  const tx = db.transaction('messages', 'readonly');
  const store = tx.store;
  const messages = await store.getAll();
  return messages.filter(m => m.userId === userId);
}

export async function clearMessages(userId) {
  const db = await dbPromise;
  const tx = db.transaction('messages', 'readwrite');
  const store = tx.store;
  const messages = await store.getAll();
  for (const message of messages) {
    if (message.userId === userId) {
      await store.delete(message.id);
    }
  }
  await tx.done;
}